#include "modelitemcoloreditor.h"
#include "ColorPickerWidget.h"

#include <QPainter>

ModelItemColorEditor::ModelItemColorEditor(QWidget *parent):
    QWidget(parent),
    m_picker(new ColorPickerWidget(this))
{
    m_picker->setWindowFlags(Qt::Popup);
    connect(m_picker, &ColorPickerWidget::colorHovered,
            this, &ModelItemColorEditor::updateBgColor);
    connect(m_picker, &ColorPickerWidget::colorClicked,
            this, &ModelItemColorEditor::closeEditor);
}

QColor ModelItemColorEditor::color() const
{
    return m_picker->selectedColor();
}

void ModelItemColorEditor::setColor(QColor color)
{
    m_picker->setSelectedColor(color);
    updateBgColor(color);
}

void ModelItemColorEditor::updateBgColor(const QColor &color)
{
    m_bgColor = color;
    update();
}

void ModelItemColorEditor::closeEditor()
{
    updateBgColor(m_picker->selectedColor());
    m_picker->hide();
    hide();
}

void ModelItemColorEditor::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    updateBgColor(m_picker->selectedColor());
    m_picker->show();
}

void ModelItemColorEditor::moveEvent(QMoveEvent *event)
{
    QWidget::moveEvent(event);
    auto globalPos = parentWidget()->mapToGlobal(geometry().bottomLeft());
    m_picker->move(m_picker->mapFromGlobal(globalPos));
}

void ModelItemColorEditor::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter painter(this);
    painter.setBrush(m_bgColor);
    painter.drawRect(rect());
}
